package com.example.librarymanagementsystembackend.advice;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.librarymanagementsystembackend.utils.InvalidRequestException;
import com.example.librarymanagementsystembackend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

public class JwtFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 不拦截permitAll的接口、Swagger接口
        if (Arrays.stream(SecurityConfig.permitAllPaths).anyMatch(antPathRequestMatcher -> antPathRequestMatcher.matches(request))) {
            chain.doFilter(request, response);
            return;
        }

        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            commitInvalidRequestException(request, response, "缺少Authorization响应头字段");
            return;
        }

        String token = authHeader.substring(7);
        String userId = JwtUtil.getValidTokenSubject(token);
        System.out.println(userId);
        if (userId == null) {
            commitInvalidRequestException(request, response, "无效token");
            return;
        }

        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(
                        userId, null, new ArrayList<>()
                )
        );

        chain.doFilter(request, response);

    }

    private void commitInvalidRequestException(HttpServletRequest request, HttpServletResponse response, String message) throws ServletException, IOException {
        request.setAttribute("originalPath", request.getRequestURI());
        request.setAttribute("invalidRequestException", new InvalidRequestException(message));
        request.getRequestDispatcher("/exception").forward(request, response);
    }
}
